package com.poem.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.poem.constant.MessageConstant;
import com.poem.dto.UserDTO;
import com.poem.dto.UsersPageQueryDTO;
import com.poem.entity.Types;
import com.poem.entity.Users;
import com.poem.exception.BaseException;
import com.poem.mapper.UsersMapper;
import com.poem.result.PageResult;
import com.poem.service.UsersService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

/**
 * @ClassName: UsersServiceImpl
 * @Author: YLY
 * @Description:
 * @Date: 2025/10/24
 * @Version: 1.0
 */
@Service
public class UsersServiceImpl implements UsersService {
    @Resource
    private UsersMapper usersMapper;

    /**
     * 查询所有用户
     * 
     * @return
     */
    public List<Users> queryAllUsers() {

        return usersMapper.queryAllUsers();
    }

    /**
     * 修改用户
     * 
     * @param userDTO
     */
    public void updateUser(UserDTO userDTO) {
        // 检查用户是否存在
        Users existingUser = usersMapper.getById(userDTO.getId());
        //获取用户名
        String username = existingUser.getUsername();
        if (existingUser == null) {
            throw new BaseException(MessageConstant.USER_ID_NOT_EXISTS);
        }

        // 检查用户名是否已存在

        usersMapper.updateUser(userDTO);
    }

    @Override
    public PageResult<Users> pageQuery(UsersPageQueryDTO usersPageQueryDTO) {

        PageHelper.startPage(usersPageQueryDTO.getPage(), usersPageQueryDTO.getPageSize());

        Page<Users> page = usersMapper.pageQuery(usersPageQueryDTO);

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 批量删除用户
     * 
     * @param ids
     */
    public void deleteBatch(List<Long> ids) {

        // 如果用户是管理员，则无法删除
        for (Long id : ids) {
            Users user = usersMapper.getById(id);
            // 获取用户名
            String username = user.getUsername();
            if ("admin".equals(user.getRole())) {
                throw new BaseException(username + MessageConstant.USER_IS_ADMIN);
            }
        }

        usersMapper.deleteBatch(ids);
    }
}
